package xy.params.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import xy.params.entity.Result;
import xy.params.entity.ResultEnum;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.*;

@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("参数异常！ msg : -> ", e);
        return new Result(400, Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }


    /**
     * 校验@RequestBody异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result bindExceptionHandler(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        Map map = new HashMap();
        for(FieldError fieldError:fieldErrors){
            //字段名
            String field = fieldError.getField();
            //字段传值错误信息
            String message = fieldError.getDefaultMessage();
            map.put(field,message);
        }
        return new Result(400,"输入参数有误", map);
    }


    /**
     * 校验@PathVariable异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> methodArgumentNotValidExceptionHandler(ConstraintViolationException e) {
        Map map = new HashMap();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = violations.iterator();
        while(iterator.hasNext()){
            ConstraintViolation<?> violation = iterator.next();
            //resultful路径
            Path path = violation.getPropertyPath();
            //字段传值错误信息
            String message = violation.getMessage();
            String p = "resultful-"+path;
            map.put(p,message);
        }
        return new Result(400,"输入参数有误", map);
    }


    /**
     * 服务器异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> exception(Exception e) {
        log.error("服务器异常！ msg: -> ", e);
        return Result.commonNoData(ResultEnum.INTERNAL_SERVER_ERROR_EXCEPTION);
    }
}
